package dfbz.com.controller.login;

import dfbz.com.constant.Const;
import dfbz.com.controller.BaseServlet;
import dfbz.com.model.User;
import dfbz.com.service.UserService;
import dfbz.com.service.impl.UserServiceImpl;
import dfbz.com.utils.MailUtil;
import dfbz.com.utils.StrUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@WebServlet("/login/*")
public class LoginServlet extends BaseServlet {

    private UserService userService = new UserServiceImpl();


    public void toLogin(HttpServletRequest req, HttpServletResponse resp) {
        try {
            String username = req.getParameter("username");
            String password = req.getParameter("password");
            String readme = req.getParameter("readme");
            if (null != username && null != password) {
                User user = userService.findUserByName(username);
                if (null != user) {
                    if (password.equals(user.getPassword())) {
                        //登录成功，接下来判断readme为不为空
                        if (null != readme) {
                            //勾选了记住
                            Cookie cookie = new Cookie("userInfo", username);
                            cookie.setMaxAge(Const.MAX_COOKIE_TIME);
                            cookie.setPath("/");
                            resp.addCookie(cookie);
                        }
                        //更新用户的登录时间
                        userService.updateLoginTime(user.getId());

                        // 登录成功后，设置会话域保存用户ID，方便过滤器做登录拦截
                        // 以及后面页面渲染的时候，获取用户基本信息时，可以拿出用户ID去写sql查询基本数据
                        req.getSession().setAttribute("userId", user.getId());

                        //这里千万别搞转发，而是重定向到UI的接口，让UI去渲染页面（使用转发）
                        resp.sendRedirect(req.getContextPath() + "/view/home");
                        return;
                    }
                }
            }
            //其余情况属于登录失败
            resp.sendRedirect(req.getContextPath() + "/");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void toLogout(HttpServletRequest req, HttpServletResponse resp) {
        try {
            Cookie[] cookies = req.getCookies();
            if (null != cookies && cookies.length > 0) {
                for (Cookie cookie : cookies) {
                    if ("userInfo".equals(cookie.getName())) {
                        cookie.setMaxAge(0);
                        cookie.setPath("/");
                        resp.addCookie(cookie);
                        break;
                    }
                }
            }
            resp.sendRedirect(req.getContextPath() + "/");
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public void toRegister(HttpServletRequest req, HttpServletResponse resp) {
        try {
            String email = req.getParameter("email");
            String username = req.getParameter("username");
            String password = req.getParameter("password");
            String password2 = req.getParameter("password2");
            //校验数据的合法性
            if (StrUtil.checkEmail(email)) {
                if (null != username && null != password) {
                    if (password.equals(password2)) {
                        //到这里检验就通过了
                        User user = userService.findUserByName(username);
                        if (null != user) {
                            //查到用这个用户了，不能注册
                            req.getSession().setAttribute("regErrorMsg", "用户已存在");
                            resp.sendRedirect(req.getContextPath() + "/view/showRegister");
                        } else {
                            User emailUser = userService.findUserByEmail(email);
                            if (null != emailUser) {
                                //查到用这个用户了，不能注册
                                req.getSession().setAttribute("regErrorMsg", "邮箱已存在");
                                resp.sendRedirect(req.getContextPath() + "/view/showRegister");
                            } else {
                                //才算是真正可以注册了，做插入数据库
                                userService.addUser(email, username, password);
                                resp.sendRedirect(req.getContextPath() + "/view/index");
                            }
                        }
                    } else {
                        req.getSession().setAttribute("regErrorMsg", "密码不一致");
                        resp.sendRedirect(req.getContextPath() + "/view/showRegister");
                    }
                } else {
                    req.getSession().setAttribute("regErrorMsg", "用户名和密码必填");
                    resp.sendRedirect(req.getContextPath() + "/view/showRegister");
                }
            } else {
                req.getSession().setAttribute("regErrorMsg", "请输入正确的邮箱");
                resp.sendRedirect(req.getContextPath() + "/view/showRegister");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    public void sendEmailCode(HttpServletRequest req, HttpServletResponse resp) {
        try {
            resp.setHeader("content-Type", "text/html");
            String email = req.getParameter("email");
            HttpSession session = req.getSession();
            //验证邮箱的合法性
            if (StrUtil.checkEmail(email)) {
                //一开始先判断session里面有没有code
                Object obj = session.getAttribute(email);
                if (null == obj) {
                    try {
                        String title = "《小标交友》重置密码";
                        String code = StrUtil.createRandomNum();
                        String content = "您的验证码是：" + code;
                        //把code放进session里
                        session.setAttribute(email, code);
                        session.setMaxInactiveInterval(Const.MAX_CODE_TIME);
                        //发送邮件
                        MailUtil.send(email, title, content, MailUtil.UNICODE);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    resp.getWriter().write("验证码发送成功，请查收");
                } else {
                    resp.getWriter().write("验证码已发送到您的邮箱了，请查收");
                }
            } else {
                resp.getWriter().write("邮箱格式不对，请重新输入");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }


    }

    public void resetPassword(HttpServletRequest req, HttpServletResponse resp) {
        try {
            String email = req.getParameter("email");
            String code = req.getParameter("emailCode");
            String password = req.getParameter("password");
            HttpSession session = req.getSession();
            if (StrUtil.checkEmail(email)) {
                Object obj = session.getAttribute(email);
                if(null != obj){
                    String emailCode = obj.toString();
                    if(emailCode.equals(code)){
                        //可以重置密码
                        User user = userService.findUserByEmail(email);
                        if(null != user){
                            userService.resetPass(user.getId(),password);
                            resp.sendRedirect(req.getContextPath() + "/view/index");
                            return;
                        }
                    }
                }

            }
            //其余情况都是失败
            req.getSession().setAttribute("forgetErrorMsg", "重置失败");
            resp.sendRedirect(req.getContextPath() + "/view/forget");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
